package com.binfoo.www.apk;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;


/**
 * Created by ZhangHongbin on 2016/11/2.
 */
public class UpdateServer {
    private final int port;

    public UpdateServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();                //1
            b.group(group)                                //2
                    .channel(NioDatagramChannel.class)            //3
                    .handler(new ChannelInitializer<DatagramChannel>() {    //4
                        @Override
                        public void initChannel(DatagramChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(
                                    new UpdateHandler());
                        }
                    }).option(ChannelOption.SO_BROADCAST, true);

            // 绑定端口，开始接收进来的连接
            ChannelFuture f = b.bind(port).sync(); // (6)

            System.out.println(("UpdateServer start listen at " + port));

            f.channel().closeFuture().await();

        } finally {
            group.shutdownGracefully().sync();            //8
        }
    }

    public static void main(String[] args) {
        try {
            new UpdateServer(6666).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
